package com.example.ymm.modules1.service.impl.ms;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.model.TableList;
import com.example.ymm.model.UserLogin;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.ms.TProviderPartner;
import com.example.ymm.modules1.entity.ms.VMaterial;
import com.example.ymm.modules1.entity.my.ms.MsMouldItem;
import com.example.ymm.modules1.entity.my.ms.MsMouldMain;
import com.example.ymm.modules1.entity.my.user.DbUser;
import com.example.ymm.modules1.mapper.my.ms.MsMouldMainMapper;
import com.example.ymm.modules1.service.dd.ms.DingNoticeService;
import com.example.ymm.modules1.service.dto.ImportMsOrderExcelDto;
import com.example.ymm.modules1.service.dto.MsOrderExcelDto;
import com.example.ymm.modules1.service.dto.ms.*;
import com.example.ymm.modules1.service.ms.*;
import com.example.ymm.modules1.service.user.DbUserService;
import com.example.ymm.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
//@Transactional
@DS("slave2")
@Slf4j
public class MsMouldMainServiceImpl extends BaseServiceImpl<MsMouldMainMapper, MsMouldMain> implements MsMouldMainService {

    @Autowired
    MsMouldItemService msMouldItemService;

    @Autowired
    MsMouldOrderService msMouldOrderService;

    @Autowired
    MsMouldDictService msMouldDictService;
    @Autowired
    VMaterialService vMaterialService;
    @Autowired
    TProviderPartnerService tProviderPartnerService;
    @Autowired
    DbUserService dbUserService;
    @Autowired
    DingNoticeService dingNoticeService;

    @Override
    public TableList<MsMouldMain> list(MsMouldMainQueryCriteria criteria, YmPageDto pageDto) {
        IPage<MsMouldMain> page = new Page<MsMouldMain>(pageDto.getPage(),pageDto.getPageSize());
        QueryWrapper predicate = QueryHelpPlus.getPredicate(MsMouldMain.class, criteria);
        predicate.orderByDesc("create_time");
        baseMapper.selectPage(page, predicate);
        TableList<MsMouldMain> tableList=new TableList(page);
        List<MsMouldMain> list = tableList.getList();
        for (MsMouldMain main:list){
            List<MsMouldItem> items = msMouldItemService.getItems(main.getMouldMainId());
            if(UtilValidate.isNotEmpty(items)){
                main.setItems(items);
                getIsReturn(main, 0);
            }
            if(main.getIsHand()==1&&UtilValidate.isEmpty(items)){
                VMaterial material = vMaterialService.findByMnameAndGuige(main.getMaterialName(), main.getSpecification());
                if(UtilValidate.isNotEmpty(material)){
                    MsMouldItem item=new MsMouldItem();
                    BeanUtils.copyProperties(material,item);
                    item.setMouldMainId(main.getMouldMainId());
                    List<MsMouldItem> lists=new ArrayList<>();
                    lists.add(item);
                    main.setItems(lists);
                    getIsReturn(main, 0);
                }else{
                    main.setSysNote("ms未录入物料信息");

                }
            }
        }
        return tableList;
    }

    public List<MsMouldMain> queryAll(MsMouldMainQueryCriteria criteria) {
        QueryWrapper predicate = QueryHelpPlus.getPredicate(MsMouldMain.class, criteria);
        predicate.orderByDesc("create_time");
        List<MsMouldMain> result =baseMapper.selectList(predicate);
        return result;
    }

    @Override
    public void addMould(MsMouldMain mouldMain) {
//        if(UtilValidate.isEmpty(mouldMain.getMouldName())){
//            throw new YmException("参数不能为空!");
//        }
        UserLogin userLogin = getUserLogin();
        mouldMain.setCreateUserId(userLogin.getId());
        mouldMain.setCreateUserName(userLogin.getUserName());
        if(UtilValidate.isNotEmpty(mouldMain.getUserId())){
            DbUser user = dbUserService.getById(mouldMain.getUserId());
            mouldMain.setUserName(user.getUserName());
        }
//        if(UtilValidate.isNotEmpty(mouldMain.getCostTypeId())){
//            MsMouldDict dict = msMouldDictService.getById(mouldMain.getCostTypeId());
//            if(UtilValidate.isNotEmpty(dict)){
//                mouldMain.setCostTypeName(dict.getName());
//            }
//        }
//        TProviderPartner provider = tProviderPartnerService.getById(mouldMain.getSupplierId());
//        if(UtilValidate.isNotEmpty(provider)){
//            mouldMain.setSupplierName(provider.getName());
//        }
        if(UtilValidate.isEmpty(mouldMain.getUserId())&&UtilValidate.isNotEmpty(mouldMain.getUserName())){
            DbUser user = dbUserService.findByUserName(mouldMain.getUserName());
            if(UtilValidate.isNotEmpty(user)){
                mouldMain.setUserId(user.getUserId());
            }

        }

        if(UtilValidate.isNotEmpty(mouldMain.getMaterialNos())){
            mouldMain.setIsRef(1);
        }



        saveOrUpdate(mouldMain);

        List<MsMouldItem> items = new ArrayList<>();
        if(UtilValidate.isNotEmpty(mouldMain.getMaterialNos())){

            String[] split = mouldMain.getMaterialNos().split(",");
            for(String s:split){
                MsMouldItem r=new MsMouldItem();
                VMaterial byNo = vMaterialService.findByNo(s);
                BeanUtils.copyProperties(byNo,r);
                r.setMouldMainId(mouldMain.getMouldMainId());
                items.add(r);
//                MsMouldOrder r=new MsMouldOrder();
//                r.setOrderNo(s);
//                r.setMouldMainId(mouldMain.getMouldMainId());
//                items.add(r);
            }
            msMouldItemService.saveOrUpdateBatch(items);
//            mouldMain.setItems(items);
//            getIsReturn(mouldMain,1);
        }

    }

    @Override
    public void editMould(MsMouldMain mouldMain) {
        UserLogin userLogin = getUserLogin();
        mouldMain.setCreateUserId(userLogin.getId());
        mouldMain.setCreateUserName(userLogin.getUserName());
        if(UtilValidate.isNotEmpty(mouldMain.getUserId())){
            DbUser user = dbUserService.getById(mouldMain.getUserId());
            mouldMain.setUserName(user.getUserName());
        }
//        if(UtilValidate.isNotEmpty(mouldMain.getCostTypeId())){
//            MsMouldDict dict = msMouldDictService.getById(mouldMain.getCostTypeId());
//            if(UtilValidate.isNotEmpty(dict)){
//                mouldMain.setCostTypeName(dict.getName());
//            }
//        }
//        TProviderPartner provider = tProviderPartnerService.getById(mouldMain.getSupplierId());
//        if(UtilValidate.isNotEmpty(provider)){
//            mouldMain.setSupplierName(provider.getName());
//        }

        if(UtilValidate.isNotEmpty(mouldMain.getMaterialNos())){
            mouldMain.setIsRef(1);
        }
        saveOrUpdate(mouldMain);


        List<MsMouldItem> items = new ArrayList<>();
        if(UtilValidate.isNotEmpty(mouldMain.getMaterialNos())){
            LambdaQueryWrapper<MsMouldItem> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(MsMouldItem::getMouldMainId,mouldMain.getMouldMainId());
            msMouldItemService.remove(queryWrapper);

            String[] split = mouldMain.getMaterialNos().split(",");
            for(String s:split){
                MsMouldItem r=new MsMouldItem();
                VMaterial byNo = vMaterialService.findByNo(s);
                BeanUtils.copyProperties(byNo,r);
                r.setMouldMainId(mouldMain.getMouldMainId());
                items.add(r);
            }

            msMouldItemService.saveOrUpdateBatch(items);
//            mouldMain.setItems(items);
//            getIsReturn(mouldMain,1);
        }

    }

   //is_send 0不通知 1通知
    @Override
    public Integer getIsReturn(MsMouldMain mouldMain,int is_send) {
        Integer result=null;//是否符合退款 0不符合 1 符合采购单 2符合外协加工单
        BigDecimal orderPrice=BigDecimal.ZERO;
        MsOrderListQueryCriteria criteria=new MsOrderListQueryCriteria();
        criteria.setSupplierId(mouldMain.getSupplierId());
        criteria.setOrderDateStart(mouldMain.getStartDate());
        criteria.setOrderDateEnd(mouldMain.getEndDate());

        BigDecimal msTotalNum=BigDecimal.ZERO;

        List<String> nos=new ArrayList<>();
        List<MsMouldItem> items = mouldMain.getItems();
        if(UtilValidate.isNotEmpty(items)){
            items.forEach(r->{
                nos.add(r.getMtid());
            });
        }
        if(UtilValidate.isEmpty(nos)){
            mouldMain.setSysNote("ms未录入物料信息");
            return result;
        }
        criteria.setMaterialNoIn(nos);
        criteria.setOrderCountType(mouldMain.getReturnConditionType());
        BigDecimal orderNumMax=null;//最大下单量/累计下单量查询;最大订单金额/累计下单金额
        if(mouldMain.getReturnConditionType()==2&&UtilValidate.isNotEmpty(mouldMain.getTotalNum())){
            orderNumMax=mouldMain.getReturnConditionNum().subtract(new BigDecimal(mouldMain.getTotalNum()));
        }else{
            orderNumMax=mouldMain.getReturnConditionNum();
        }
      //  criteria.setOrderNumMax(orderNumMax); //数量或者金额的筛选 关闭 sql判断 改用手工判断;criteria.setOrderNumMax 不传 sql就不会进行判断

        //       //退款条件 1一次性(数量)  4一次性(金额)
        if(mouldMain.getReturnConditionType()==1||mouldMain.getReturnConditionType()==4){

            List<MsOrderDto> msOrderDtos = tProviderPartnerService.purchaseOrderList(criteria);
            if(UtilValidate.isNotEmpty(msOrderDtos)){
//                orderPrice=msOrderDtos.get(0).getOrderPrice();
//                result=1;
                for(MsOrderDto r:msOrderDtos){
//                    System.out.println("--输出:"+r.toString());
                    if(UtilValidate.isEmpty(mouldMain.getSupplierId())){
                        mouldMain.setSupplierId(r.getSupplierId());
                    }
                    // 1一次性(数量)
                    if(mouldMain.getReturnConditionType()==1){
                        int i =  new BigDecimal(r.getOrderNum()).compareTo(orderNumMax);
                        if(i>=0){
                            result=1;
                        }
                        if(UtilValidate.isEmpty(msTotalNum)){
                            msTotalNum=new BigDecimal(r.getOrderNum());
                        }else{
                            //取最大值
                            int i1 = new BigDecimal(r.getOrderNum()).compareTo(msTotalNum);
                            if(i1>=0){
                                msTotalNum=new BigDecimal(r.getOrderNum());
                            }
                        }
                    }
                    // 4一次性(金额)
                    if(mouldMain.getReturnConditionType()==4){
                        int i = r.getOrderPrice().compareTo(orderNumMax);
                        if(i>=0){
                            result=1;
                        }
                        if(UtilValidate.isEmpty(msTotalNum)){
                            msTotalNum=r.getOrderPrice();
                        }else{
                            //取最大值
                            int i1 = r.getOrderPrice().compareTo(msTotalNum);
                            if(i1>=0){
                                msTotalNum=r.getOrderPrice();
                            }
                        }
                    }
                }

            }else{
                if(mouldMain.getReturnConditionType()==1){
                    List<MsOrderDto>  msOrderDtos2 = tProviderPartnerService.outsourceOrderList(criteria);
                    if(UtilValidate.isNotEmpty(msOrderDtos2)){

                        for(MsOrderDto r:msOrderDtos2){
                            // 1一次性(数量)
                            if(mouldMain.getReturnConditionType()==1){
                                int i =  new BigDecimal(r.getOrderNum()).compareTo(orderNumMax);
                                if(i>=0){
                                    result=2;
                                }
                                if(UtilValidate.isEmpty(msTotalNum)){
                                    msTotalNum=new BigDecimal(r.getOrderNum());
                                }else{
                                    //取最大值
                                    int i1 = new BigDecimal(r.getOrderNum()).compareTo(msTotalNum);
                                    if(i1>=0){
                                        msTotalNum=new BigDecimal(r.getOrderNum());
                                    }
                                }
                            }
                            // 4一次性(金额)
                            if(mouldMain.getReturnConditionType()==4){
                                int i = r.getOrderPrice().compareTo(orderNumMax);
                                if(i>=0){
                                    result=2;
                                }
                                if(UtilValidate.isEmpty(msTotalNum)){
                                    msTotalNum=r.getOrderPrice();
                                }else{
                                    //取最大值
                                    int i1 = r.getOrderPrice().compareTo(msTotalNum);
                                    if(i1>=0){
                                        msTotalNum=r.getOrderPrice();
                                    }
                                }
                            }
                        }

                    }
                }

            }
        }else if(mouldMain.getReturnConditionType()==2||mouldMain.getReturnConditionType()==5){
               //退款条件类别:  2累计(数量)  5累计(金额)

            Double aDouble = tProviderPartnerService.purchaseOrderSum(criteria);
            if(UtilValidate.isNotEmpty(aDouble)&&aDouble>0){
                msTotalNum=new BigDecimal(aDouble);
                int i1 = msTotalNum.compareTo(orderNumMax);
                if(i1>=0){
                    result=1;
                }

            }else{
                if(mouldMain.getReturnConditionType()==2){
                    //采购单累计下单量统计
                    Double aDouble2 = tProviderPartnerService.outsourceOrderSum(criteria);
                    if(UtilValidate.isNotEmpty(aDouble2)&&aDouble2>0){
                        msTotalNum=new BigDecimal(aDouble);
                        int i1 = msTotalNum.compareTo(orderNumMax);
                        if(i1>=0){
                            result=2;
                        }
                    }
                }

            }
        }

        mouldMain.setMsTotalNum(msTotalNum);


        if(UtilValidate.isNotEmpty(result)){
            mouldMain.setIsReturn(result);
//            mouldMain.setOrderPrice(orderPrice);
 //           saveOrUpdate(mouldMain);
            if(is_send!=0){
                dingNoticeService.OATempleNotice(mouldMain);
            }
        }


        return result;
    }

    @Override
    public MsMouldMain detailMould(String mouldMainId) {
        MsMouldMain msMouldMain = getById(mouldMainId);
        MsMouldItemQueryCriteria criteria=new MsMouldItemQueryCriteria();
        criteria.setMouldMainId(msMouldMain.getMouldMainId());
        List<MsMouldItem> msMouldItems = msMouldItemService.queryAll(criteria);
        msMouldMain.setItems(msMouldItems);
        List<String> nos=new ArrayList<>();
        if(UtilValidate.isNotEmpty(msMouldItems)){
            msMouldItems.forEach(r->{
                nos.add(r.getMtid());
            });
            msMouldMain.setMaterialNos(String.join(",",nos));
        }
    //
        return msMouldMain;
    }

    @Override
    public void deleteMould(String mouldMainId) {
        LambdaQueryWrapper<MsMouldItem> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(MsMouldItem::getMouldMainId,mouldMainId);
        msMouldItemService.remove(queryWrapper);
        removeById(mouldMainId);
    }

    public void operatorMouldData(MsMouldMain msMouldMain, int is_send){
        MsMouldItemQueryCriteria criteria=new MsMouldItemQueryCriteria();
        criteria.setMouldMainId(msMouldMain.getMouldMainId());
        List<MsMouldItem> msMouldItems = msMouldItemService.queryAll(criteria);
//        List<MsMouldItem> items=new ArrayList<>();
//        List<String> orderNoIns=new ArrayList<>();
//        msMouldItems.forEach(r->{
//            orderNoIns.add(r.getOrderNo());
//        });
//        if(UtilValidate.isNotEmpty(orderNoIns)){
//            MsOrderListQueryCriteria orderListQuery=new MsOrderListQueryCriteria();
//            orderListQuery.setOrderNoIn(orderNoIns);
//            items=tProviderPartnerService.purchaseOrderList(orderListQuery);
//
//        }
        if(UtilValidate.isNotEmpty(msMouldItems)){
            msMouldMain.setItems(msMouldItems);
            getIsReturn(msMouldMain,is_send);
        }else{
            if(msMouldMain.getIsHand()==1&&UtilValidate.isEmpty(msMouldItems)){
                VMaterial material = vMaterialService.findByMnameAndGuige(msMouldMain.getMaterialName(), msMouldMain.getSpecification());
                if(UtilValidate.isNotEmpty(material)){
                    MsMouldItem item=new MsMouldItem();
                    BeanUtils.copyProperties(material,item);
                    item.setMouldMainId(msMouldMain.getMouldMainId());
                    List<MsMouldItem> items=new ArrayList<>();
                    items.add(item);
                    msMouldMain.setItems(items);
                    getIsReturn(msMouldMain, 0);
                }
            }
        }

    }


    @Override
    public void syncNoticeAllMain() {

        List<MsMouldMain> msMouldMains = getNoticeAllMain();
        for(MsMouldMain main: msMouldMains){
            operatorMouldData(main,1);
        }
    }


    @Override
    public MsMouldMain findOrderNo(String orderNo) {
        MsMouldMainQueryCriteria criteria=new MsMouldMainQueryCriteria();
        criteria.setOrderNo(orderNo);
        MsMouldMain result=null;

        List<MsMouldMain> msMouldMains = queryAll(criteria);
        if(UtilValidate.isNotEmpty(msMouldMains)){
            result=msMouldMains.get(0);
        }
        return result;
    }

    @Override
    @Transactional(propagation=Propagation.REQUIRES_NEW)
    public List<String> getOrderNos(MsMouldMainQueryCriteria criteria) {
        return baseMapper.getOrderNos(criteria);
    }


    @Override
    @DSTransactional
    public List<Map<String,Object>> importMsOrder(ImportMsOrderExcelDto dto) {
        List<MsOrderExcelDto> list = dto.getList();
        List<Map<String,Object>> ms=new ArrayList<>();
        Map<String,DbUser> userMap=new HashMap<>();
        for(int a=0;a<list.size();a++){
            MsOrderExcelDto excelDto = list.get(a);

            StringBuffer buffer=new StringBuffer();
            if(UtilValidate.isEmpty(excelDto.getMouldName())&&UtilValidate.isEmpty(excelDto.getMaterialName())){
                continue;
            }
            if(UtilValidate.isEmpty(excelDto.getMouldName())){
                buffer.append("型号不能为空");
            }
            if(UtilValidate.isEmpty(excelDto.getMaterialName())){

                buffer.append(" 物料名称不能为空");
            }
            if(UtilValidate.isEmpty(excelDto.getPrice())){
                buffer.append(" 金额不能为空");
            }
            if(UtilValidate.isEmpty(excelDto.getSupplierName())){

                buffer.append(" 供应商名称不能为空");
            }

            if(UtilValidate.isEmpty(excelDto.getStartDate())){

                buffer.append(" 开始日期不能为空");
            }
            if(UtilValidate.isNotEmpty(excelDto.getStartDate())){
                Date date = DateKit.dateFormat(excelDto.getStartDate() + " 00:00:00");
                if(UtilValidate.isEmpty(date)){
                    buffer.append(" 开始日期格式有误 请将excel中该列格式设置为yyyy-MM-dd的日期格式");
                }
            }
            if(UtilValidate.isNotEmpty(excelDto.getEndDate())){
                Date date = DateKit.dateFormat(excelDto.getEndDate() + " 00:00:00");
                if(UtilValidate.isEmpty(date)){
                    buffer.append(" 结束日期格式有误 请将excel中该列格式设置为yyyy-MM-dd的日期格式");
                }
            }

            if(UtilValidate.isEmpty(excelDto.getReturnConditionType())){

                buffer.append(" 退款条件类型不能为空");

            }
            if(UtilValidate.isEmpty(excelDto.getReturnConditionNum())){

                buffer.append(" 退款条件数量不能为空");
            }
//            if(UtilValidate.isEmpty(excelDto.getUserType())){
//
//                buffer.append(" 人员类型不能为空");
//            }
            if(UtilValidate.isNotEmpty(excelDto.getUserName())){
                DbUser user = dbUserService.findByUserName(excelDto.getUserName());
                if(UtilValidate.isEmpty(user)){

                    buffer.append(" 经办人名称有误");
                }else{
                    userMap.put(excelDto.getUserName(),user);
                }
            }

            if(UtilValidate.isNotEmpty(buffer.toString())){
                Map<String,Object> map=new HashMap<>();
                map.put("index",a+1+2);
                map.put("message",buffer.toString());
                ms.add(map);
            }

        }
        List<MsMouldMain> batchList=new ArrayList<>();
        if(UtilValidate.isEmpty(ms)){

            String userId = getUserId();
            String userName = getUserName();

            DynamicDataSourceContextHolder.push("slave");

            for(MsOrderExcelDto excelDto:list){
                String supplierName = excelDto.getSupplierName().trim();
                excelDto.setSupplierName(supplierName);
                excelDto.setUserName(excelDto.getUserName().trim());
                excelDto.setMouldName(excelDto.getMouldName().trim());
                excelDto.setMaterialName(excelDto.getMaterialName().trim());
                if(UtilValidate.isNotEmpty(excelDto.getSpecification())){
                    excelDto.setSpecification(excelDto.getSpecification());
                }
                if(UtilValidate.isEmpty(excelDto.getMouldName() )&&UtilValidate.isEmpty(supplierName)){
                    continue;
                }
                if(excelDto.getEndDate()!=null){
                    if("".equals(excelDto.getEndDate().trim())){
                        excelDto.setEndDate(null);
                    }

                }
                MsMouldMain main=new MsMouldMain();
                BeanUtils.copyProperties(excelDto,main);
                TProviderPartner supplier = tProviderPartnerService.findLikeName(excelDto.getSupplierName());
                if(UtilValidate.isNotEmpty(supplier)){
                    main.setSupplierId(supplier.getOid());
                    main.setSupplierName(supplier.getName());
                }
                main.setUserName(excelDto.getUserName());
                main.setModel(main.getMouldName());
                if(userMap.containsKey(excelDto.getUserName())){
                    DbUser user = userMap.get(excelDto.getUserName());
                    main.setUserId(user.getUserId());
                }
                VMaterial vMaterial = vMaterialService.findByMnameAndGuige(excelDto.getMaterialName(), excelDto.getSpecification());
                if(UtilValidate.isNotEmpty(vMaterial)){
                    main.setIsRef(1);
                    MsMouldItem item=new MsMouldItem();
                    item.setMname(vMaterial.getMname());
                    item.setGuige(vMaterial.getGuige());
                    item.setMmodel(vMaterial.getMmodel());
                    item.setMtid(vMaterial.getMtid());
                    List<MsMouldItem> items=new ArrayList<>();
                    items.add(item);
                    main.setItems(items);
                }
                main.setIsHand(1);
                Integer type=null;
//                switch (excelDto.getReturnConditionType()){
//                    case "一次性(数量)":
//                        type=1;
//                        break;
//                    case "累计(数量)":
//                        type=2;
//                        break;
//                    case "一次性(金额)":
//                        type=4;
//                        break;
//                    case "累计(金额)":
//                        type=5;
//                        break;
//                    case "不退":
//                        type=3;
//
//                        break;
//                }
                String c_type=excelDto.getReturnConditionType();
                if(c_type.contains("一次性")&&c_type.contains("数量")){
                    type=1;
                }
                if(c_type.contains("累计")&&c_type.contains("数量")){
                    type=2;
                }
                if(c_type.contains("一次性")&&c_type.contains("金额")){
                    type=3;
                }
                if(c_type.contains("累计")&&c_type.contains("金额")){
                    type=5;
                }
                if(type==3){
                    continue;
                }

//                Integer userType=null;
//                switch (excelDto.getUserType()){
//                    case "采购员":
//                        type=1;
//                        break;
//                    case "研发制样员":
//                        type=2;
//                        break;
//                }
//                main.setUserType(userType);
                main.setReturnConditionType(type);
                main.setCreateUserId(userId);
                main.setCreateUserName(userName);
                batchList.add(main);

            }
            DynamicDataSourceContextHolder.clear();
            DynamicDataSourceContextHolder.push("master");
        }

//        saveOrUpdateBatch(batchList);
        for(MsMouldMain main:batchList){
            saveOrUpdate(main);
            if(UtilValidate.isNotEmpty(main.getItems())){
                for(MsMouldItem item:main.getItems()){
                    item.setMouldMainId(main.getMouldMainId());
                    msMouldItemService.saveOrUpdate(item);
                }
            }
        }

        return ms;
    }


    @Override
    public List<MsMouldMain> getNoticeAllMain() {
        MsMouldMainQueryCriteria criteria=new MsMouldMainQueryCriteria();
        return baseMapper.getNoticeAllMain(criteria);
    }

    @Override
    public Integer getMyWaitList() {
        Integer result=0;
        MsMouldMainQueryCriteria criteria=new MsMouldMainQueryCriteria();
        String userId = getUserId();
        criteria.setUserId(userId);
        List<MsMouldMain> list = baseMapper.getNoticeAllMain(criteria);
        for (MsMouldMain main:list){
            List<MsMouldItem> items = msMouldItemService.getItems(main.getMouldMainId());
            if(UtilValidate.isNotEmpty(items)){
                main.setItems(items);
                getIsReturn(main, 0);
                if(main.getIsReturn()>0){
                    result++;
                }
            }
        }
        return result;
    }


    /**
     * 自动创建虚拟采购单
     */
    @Override
    public void autoCreateOrderFn() {
        MsOrderListQueryCriteria criteria=new MsOrderListQueryCriteria();
        criteria.setIfXuNiJian(1);
        List<MsOrderDto> msOrderDtos = tProviderPartnerService.purchaseOrderList(criteria);
        for(MsOrderDto msOrderDto:msOrderDtos){
            autoCreateOne(msOrderDto);
        }

    }

    public void autoCreateOne(MsOrderDto msOrderDto){
        MsMouldMain main=new MsMouldMain();
        BeanUtils.copyProperties(msOrderDto,main);
        main.setCreateTime(null);
        main.setMouldName(msOrderDto.getModel());
        main.setPrice(msOrderDto.getOrderPrice());
        main.setStartDate(msOrderDto.getOrderDate());
        String remark = msOrderDto.getRemark();

        Integer returnConditionType=null;
        BigDecimal returnConditionNum=null;
        if (UtilValidate.isNotEmpty(remark) && remark.contains("&")) {
            String[] arr = remark.split("&");
            Integer type = null;
            String type_txt = arr[0];

            // 退款条件类别:  1一次性(数量) 2累计(数量) 3不退 4一次性(金额) 5累计(金额)
            if(type_txt.contains("一次性")&&type_txt.contains("数量")
                    ||type_txt.contains("一次性")&&type_txt.contains("数量")
            ){
                type = 1;
            }
            if(type_txt.contains("累计")&&type_txt.contains("数量")
                    ||type_txt.contains("累计")&&type_txt.contains("数量")
            ){
                type = 2;
            }
            if(type_txt.contains("一次性")&&type_txt.contains("金额")){
                type = 4;
            }
            if(type_txt.contains("累计")&&type_txt.contains("金额")){
                type = 5;
            }
            if(type_txt.contains("不退还")){
                type = 3;
            }
            returnConditionType = type;
//            StringUtils.inStringIgnoreCase()
            returnConditionNum = new BigDecimal(StringUtils.getNumberVal(arr[1]));
        }
        main.setReturnConditionType(returnConditionType);
        main.setReturnConditionNum(returnConditionNum);
        saveOrUpdate(main);
    }
}
